import * as ol from "ol";
import * as keys from "./keys";
import { log } from "./log";
import { OverlayOptions } from "./types";
import { getMap } from "./instance";

// 地图弹窗 id
let overlayId = 0;

/**
 * @description: 渲染弹窗
 * @param {OverlayOptions} options 配置项
 * @returns
 */
export const renderOverlay = (options: OverlayOptions): number => {
  const mapInstance = getMap();
  if (!mapInstance) {
    throw new Error("地图实例未初始化");
  }

  log("Render Overlay", options);

  const id = ++overlayId;
  const overlay = new ol.Overlay(options);
  overlay.set(keys.OVERLAY_ID_KEY, id);
  overlay.set(keys.OPTIONS_KEY, options);
  mapInstance.addOverlay(overlay);

  return id;
};

/**
 * @description:
 * @param {number} id
 */
export const queryOverlay = (id: number): ol.Overlay | undefined => {
  const mapInstance = getMap();
  if (!mapInstance) {
    throw new Error("地图实例未初始化");
  }

  return mapInstance
    .getOverlays()
    .getArray()
    .find((overlay) => overlay.get(keys.OVERLAY_ID_KEY) === id);
};

/**
 * @description: 移除弹窗
 * @param {number} id 弹窗主键
 * @returns
 */
export const removeOverlay = (id: number): void => {
  const mapInstance = getMap();
  if (!mapInstance) {
    throw new Error("地图实例未初始化");
  }

  const overlay = mapInstance
    .getOverlays()
    .getArray()
    .find((o) => o.get(keys.OVERLAY_ID_KEY) === id);
  if (overlay) {
    log("Remove Overlay", id);
    mapInstance.removeOverlay(overlay);
  }
};
